<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Website;
use app\model\Channel;
use app\model\Customer;
use app\model\Principal;

class Sem extends Common
{

	/**
	* 获取百度站点ID列表
	*
	* @param tValue
	* @return
	*/
	private function getSiteList($data) {
		$request = doPostRequest('https://api.baidu.com/json/tongji/v1/ReportService/getSiteList', $data);
		if(empty($request)) {
			return false;
		}
		$response = json_decode($request, true);
		if(!is_array($response)) {
			return false;
		}
		if( !isset($response['header']['desc']) ) {
			return false;
		}
		$result = [];
		$result['lastDatetime'] = date('Y-m-d H:i:s');
		if($response['header']['desc'] == 'success' ) {
			$siteArray = [];
			foreach ( $response['body']['data'][0]['list'] as $value ) {
				if( stripos($value['domain'], 'aisite.wejianzhan.com') === false ) {
					array_push($siteArray, $value['site_id']);
				}
			}
			$result['countStat'] = 0;
			$result['countMessage'] = '';
			$result['siteid'] = implode(',', $siteArray);
			$result['countRquota'] = $response['header']['rquota'];
			return $result;
		}
		$result['siteid'] = '';
		$result['countRquota'] = 0;
		$result['countStat'] = 999;
		$result['countMessage'] = serialize($response['header']['failures'][0]);
		return $result;
	}

	/**
	* 获取百度账户信息
	*
	* @param tValue
	* @return
	*/
	private function getAccountInfo($data) {
		$request = doPostRequest('https://api.baidu.com/json/sms/service/AccountService/getAccountInfo', $data);
		if(empty($request)){
			return false;
		}
		$response = json_decode($request, true);
		if(!is_array($response)){
			return false;
		}
		if(!isset($response['header']['desc'])) {
			return false;
		}
		$result = [];
		$result['lastDatetime'] = date('Y-m-d H:i:s');
		if($response['header']['desc'] == 'success' ) {
			$result['userMessage'] = '';
			$result['userRquota'] = $response['header']['rquota'];
			$result['cost'] = $response['body']['data'][0]['cost'];
			$result['userid'] = $response['body']['data'][0]['userId'];
			$result['budget'] = $response['body']['data'][0]['budget'];
			$result['balance'] = $response['body']['data'][0]['balance'];
			$result['userStat'] = $response['body']['data'][0]['userStat'];
			$result['userLevel'] = $response['body']['data'][0]['userLevel'];
			return $result;
		}
		$result['userStat'] = 888;
		$result['userRquota'] = 0;
		$result['userMessage'] = serialize($response['header']['failures'][0]);
		return $result;
	}


	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'sem:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'balance', 'trim');
		$order = $request->param('order', 'asc', 'trim');

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['userType', '=', 1 ] );

		$username = $request->param('username', '', 'trim');
		if($username) {
			array_push( $where, ['username', 'like',  "%{$username}%" ] );
		}

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['','exp', Db::raw("FIND_IN_SET({$bazaarId}, bazaarId)")] );
		}

		$domainIds = $request->param('domainIds', '', 'trim');
		if($domainIds) {
			array_push( $where, ['domainIds', 'like',  "%{$domainIds}%" ] );
		}

		$ocpcType = $request->param('ocpcType', '', 'trim');
		if($ocpcType) {
			array_push( $where, ['ocpcType', '=',  $ocpcType ] );
		}

		$userStat = $request->param('userStat', '', 'trim');
		if($userStat) {
			array_push( $where, [ $userStat == 888 ? 'userStat' : 'countStat', '=',  $userStat ] );
		}

		$channelid = $request->param('channelid', '', 'trim');
		if($channelid) {
			array_push( $where, ['channelid', '=',  $channelid ] );
		}

		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['customerid', '=',  $customerid ] );
		}

		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $where, ['contact', '=',  $contact ] );
		}
        //权限管理
		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('semauthaccount');
			if($authaccount) {
				array_push( $where, ['userid', 'in',  $authaccount ] );
			}
		}
		
		$query = Db::name('cfg_expand')->where($where)->order($sort, $order)->paginate($limit);

		$count = $query->total();
		$items = $query->items();
		foreach($items as &$value) {
			unset($value['regionTarget']);
			$value['domainIds'] = explode(',', $value['domainIds']);
			if( strlen($value['cpa']) > 20) {
				$value['cpa'] = unserialize($value['cpa']);
			} else {
				$value['cpa'] = [
					"userValue" =>0,
					"planValue"=>0,
					"unitValue"=>0,
					"mobileValue"=>'',
					"balanceValue"=>0,
					"creativeValue"=>0
				];
			}
			if( strlen($value['countMessage']) > 20) {
				$value['countMessage'] = unserialize($value['countMessage']);
			}
			if( strlen($value['userMessage']) > 20) {
				$value['userMessage'] = unserialize($value['userMessage']);
			}
		}

		unset($query, $value);

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items,
		'website' => Website::getList($request->sessInfo),
		'channel' => Channel::getList($request->sessInfo),
		'customer' => Customer::getList($request->sessInfo),
		'principal' => Principal::getList($request->sessInfo),
		'bazaar' => Bazaar::getList($request->sessInfo, 1) ];
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'sem:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$param = $request->param();
		if( isset($param['state']) ) {
			$status = $request->param('status', '', 'trim');
			$beginTime = microtime(true);
			$statusName = $status ? '正常状态' :  '停用状态';
			$row = Db::table('cfg_expand')->field('username, status')->where('id', $param['state'])->where('companyId', $request->sessInfo['companyId'])->find();
			Db::name('cfg_expand')->where('id', $param['state'])
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'status' => $status]);
			if( isset($row['username'])) {
				$row['status'] = $row['status'] ? '正常状态' :  '停用状态';
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM竞价', "推广账号[{$row['username']}]状态从[{$row['status']}]改为[{$statusName}]", 0, null);
			}
			return ['code'=>0, 'msg'=>'操作成功!'];
		}

		$id = $request->param('id', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$userType = $request->param('userType', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$token = $request->param('token', '', 'trim');
		$ocpc = $request->param('ocpc', '', 'trim');
		$ocpcCode = $request->param('ocpcCode', '', 'trim');
		$contact = $request->param('contact', '', 'trim');
		$channelid = $request->param('channelid', '', 'trim');
		$customerid = $request->param('customerid', '', 'trim');
		$ocpcType = $request->param('ocpcType', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$rebate = $request->param('rebate', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$siteid = $request->param('siteid', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$domainIds = $request->param('domainIds', '', 'trim');
		$ocpcTime = $request->param('ocpcTime/d', '', 'trim');
		$sqldomain = implode(',', $domainIds);

		if(empty($username)) {
			return ['code'=>403, 'msg'=>'推广账号不能为空!'];
		}

		if(empty($password)) {
			return ['code'=>403, 'msg'=>'推广密码不能为空!'];
		}

		$sqlInsert = [ 'bazaarId' => $bazaarId, 'token' => $token, 'ocpcCode' => $ocpcCode, 'domainIds' => $sqldomain, 'ocpc' => $ocpc, 'ocpcType' => $ocpcType, 'channelid' => $channelid, 'customerid' => $customerid, 'contact' => $contact,
		'userType' => $userType, 'password' => $password, 'rebate' => $rebate, 'remark' => $remark, 'siteid' => $siteid, 'ocpcTime' => $ocpcTime ];
		$baiduUserArray = $this->getAccountInfo(json_encode(['header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
		  'body'=> [ 'accountFields'=> [ 'regionTarget', 'mobileBalance', 'budgetType', 'pcBalance', 'userStat', 'balance', 'budget', 'cost', 'userId', 'regDomain', 'userLevel' ] ]]));
		if($baiduUserArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduUserArray);
		}

		$baiduSiteArray = $this->getSiteList(json_encode(['header' => [ 'username'=> $username, 'password'=> $password, 'token'=> $token, 'account_type'=> 1]]));
		if($baiduSiteArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduSiteArray);
		}

		Db::name('cfg_expand')->where('id', $id)
		->where('companyId', $request->sessInfo['companyId'])->update($sqlInsert);
		return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'sem:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$userType = $request->param('userType', '', 'trim');
		$token = $request->param('token', '', 'trim');
		$ocpc = $request->param('ocpc', '', 'trim');
		$ocpcTime = $request->param('ocpcTime/d', '', 'trim');
		$ocpcCode = $request->param('ocpcCode', '', 'trim');
		$contact = $request->param('contact', '', 'trim');
		$channelid = $request->param('channelid', '', 'trim');
		$customerid = $request->param('customerid', '', 'trim');
		$ocpcType = $request->param('ocpcType', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$rebate = $request->param('rebate', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$siteid = $request->param('siteid', '', 'trim');

		if(empty($username)) {
			return ['code'=>403, 'msg'=>'推广账号不能为空!'];
		}

		if(empty($password)) {
			return ['code'=>403, 'msg'=>'推广密码不能为空!'];
		}

		$bazaarId = $request->param('bazaarId', '', 'trim');
		$domainIds = $request->param('domainIds', '', 'trim');
		$sqldomain = implode(',', $domainIds);

		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])
			->where('username', $username)->value('username');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'推广账号已存在!'];
		}

		$sqlInsert = [ 'bazaarId' => $bazaarId, 'companyId' => $request->sessInfo['companyId'], 'ocpcCode' => $ocpcCode, 'username' => $username, 'token' => $token, 'domainIds' => $sqldomain, 'ocpc' => $ocpc, 'channelid' => $channelid, 'customerid' => $customerid, 'contact' => $contact,
			'ocpcType' => $ocpcType, 'password' => $password, 'rebate' => $rebate, 'remark' => $remark, 'siteid' => $siteid, 'ocpcTime' => $ocpcTime, 'userType' => $userType, 'datatime' => date('Y-m-d H:i:s') ];
		$baiduUserArray = $this->getAccountInfo(json_encode(['header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
		  'body'=> [ 'accountFields'=> [ 'regionTarget', 'mobileBalance', 'budgetType', 'pcBalance', 'userStat', 'balance', 'budget', 'cost', 'userId', 'regDomain', 'userLevel' ] ]]));
		if($baiduUserArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduUserArray);
		}

		$baiduSiteArray = $this->getSiteList(json_encode(['header' => [ 'username'=> $username, 'password'=> $password, 'token'=> $token, 'account_type'=> 1]]));
		if($baiduSiteArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduSiteArray);
		}
		Db::name('cfg_expand')->insert($sqlInsert);

		return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'sem:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$beginTime = microtime(true);
		$deleteArray = [];
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			$query = Db::table('cfg_expand')->field('id,username,userid')->where('id', $value)->where('companyId', $request->sessInfo['companyId'])->find();
			if(isset($query['id'])){
				array_push($deleteArray, $query['username']);
				Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('id', $value)->delete();
				Db::table('cfg_area')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_hours')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_access')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_search')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_optlog')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
				Db::table('cfg_adgroup')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
				Db::table('cfg_campaign')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
				Db::table('cfg_creative')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
			}
		}
		unset($explode, $value);
		foreach( $deleteArray as $value ) {
			if( $value ) {
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM竞价', '删除推广账号['.$value.']', 0, json_encode($param));
			}
		}
		unset($deleteArray, $value);
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

	/**
	 * 更新CPA
	 *
	 * @return
	 */
	public function updateCpa(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:cpa')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$cpa = $request->param('cpa', '', 'trim');
		Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update(['cpa' => serialize($cpa) ]);
		return ['code'=> 0, 'msg'=> '操作成功!'];
	}

	/**
	 * 设置账户预算
	 *
	 * @return
	 */
	public function updateBudget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:budget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$token = $request->param('token', '', 'trim');
		$budget = $request->param('budget', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$budgetType = $request->param('budgetType', '', 'trim');
		if( $budgetType == 0 ) {
			$budget = 0;
		}

		$budgetDate = Db::table('cfg_expand')->where('id', $id )->where('companyId', $request->sessInfo['companyId'])->value('budgetDate');
		if($budgetDate){
			$isBudgetDate = time() - strtotime($budgetDate);
			if( $isBudgetDate < 300){
				return ['code'=> 403, 'msg'=> '5分钟内只能修改1次预算设置，请不要频繁修改!'];
			}
		}

		$updateAccountInfo = [
			'header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
			'body'=>[ 'accountInfo' =>	[
				'budget'=> $budget,
				'budgetType'=> $budgetType
			]
		]];

		$result = doPostRequest('https://api.baidu.com/json/sms/service/AccountService/updateAccountInfo', json_encode($updateAccountInfo));
		if(empty($result)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		$response = json_decode($result, true);
		if(!is_array($response)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
    if(!isset($response['header'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
    if(!isset($response['header']['desc'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		if($response['header']['desc'] == 'success') {
			Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update([
				'budget'=> $budget,
				'budgetType'=> $budgetType,
				'budgetDate'=> date('Y-m-d H:i:s'),
			]);
			return ['code'=> 0, 'msg'=> '操作成功!'];
		}
    if(!isset($response['header']['failures'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		return ['code'=> 403, 'msg'=> $response['header']['failures'][0]['code'] . ': '. $response['header']['failures'][0]['message']];
	}

	/**
	 * 设置账户OCPC出价
	 *
	 * @return
	 */
	public function updateOcpcBid(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:ocpcbid')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$ocpcBid = $request->param('maxPrice', '', 'trim');
		if(empty($ocpcBid)) {
			return ['code'=>403, 'msg'=>'目标转化出价不能为空!'];
		}

		$userInfo = Db::table('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->find();
    if(!isset($userInfo['id'])){
			return ['code'=> 403, 'msg'=> '账户ID不存在!'];
		}

		$getTargetPackageList = [
			'header'=> [ 'username'=> $userInfo['username'], 'password'=> $userInfo['password'], 'token'=> $userInfo['token'] ],
			'body'=>[
				'targetPackageTypeFields' =>	[ "targetPackageId", "targetPackageName", "ocpcBid", "ocpcBidType", "ecpcMaxBidRatio", "scope", "dataFlowData", "equipmentType", "ocpcStage",
				"assistTransTypes", "ocpcDeepCpa", "astat", "wiseAuditTime", "packageStatus", "deepTypeStat", "deepTransTypeMode", "adoptNoThreshold" ],
				'ids' =>	[ 1	],
				'level' => 1
		]];

		$getOcpcService = doPostRequest('https://api.baidu.com/json/sms/service/OcpcService/getTargetPackageList', json_encode($getTargetPackageList));
		if(empty($getOcpcService)) {
			return ['code'=> 403, 'msg'=> $userInfo['username'] . '查询失败通信异常!'];
		}

		$response = json_decode($getOcpcService, true);
		if(!is_array($response)) {
			return ['code'=> 403, 'msg'=> $userInfo['username'] . '查询失败通信异常!'];
		}

    if(!isset($response['header'])){
			return ['code'=> 403, 'msg'=> $userInfo['username'] . '查询失败通信异常!'];
		}

    if(!isset($response['header']['desc'])) {
			return ['code'=> 403, 'msg'=> $userInfo['username'] . '查询失败通信异常!'];
		}

		if($response['header']['desc'] == 'success') {

			$scopeArray = [];
			if( is_array($response['body']['data'][0]['scope']) ) {
				foreach($response['body']['data'][0]['scope'] as $value) {
					array_push($scopeArray, ['levelId' => $value['levelId'], 'level' => $value['level'] ]);
				}
			}

			$updateTargetPackage = [
				'header'=> [ 'username'=> $userInfo['username'], 'password'=> $userInfo['password'], 'token'=> $userInfo['token'] ],
				'body'=>[
					"targetPackageType"=> [
						[
							"targetPackageId"=> $response['body']['data'][0]['targetPackageId'],
							"ocpcBidType"=> $response['body']['data'][0]['ocpcBidType'],
							"ocpcBid"=> $ocpcBid,
							"scope"=> $scopeArray,
							"adoptNoThreshold"=> $response['body']['data'][0]['adoptNoThreshold']
						]
					]
			]];

			$result = doPostRequest('https://api.baidu.com/json/sms/service/OcpcService/updateTargetPackage', json_encode($updateTargetPackage));
			if(empty($result)) {
				return ['code'=> 403, 'msg'=> $userInfo['username'] . '更新失败通信异常!'];
			}

			$response = json_decode($result, true);
			if(!is_array($response)) {
				return ['code'=> 403, 'msg'=> $userInfo['username'] .  '更新失败通信异常!'];
			}

			if($response['header']['desc'] == 'success') {
				Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update(['ocpcBid'=> $ocpcBid]);
				return ['code'=> 0, 'msg'=> $userInfo['username'] . '操作成功!'];
			}

			if(!isset($response['header']['failures'])){
				return ['code'=> 403, 'msg'=> $userInfo['username'] . '更新失败通信异常!'];
			}
			return ['code'=> 403, 'msg'=> $userInfo['username'] . $response['header']['failures'][0]['code'] . ': '. $response['header']['failures'][0]['message']];
		}

    if(!isset($response['header']['failures'])) {
			return ['code'=> 403, 'msg'=> $userInfo['username'] .  '查询失败通信异常!'];
		}

		return ['code'=> 403, 'msg'=> $userInfo['username'] . $response['header']['failures'][0]['code'] . ': '. $response['header']['failures'][0]['message']];
	}


	/**
	 * 设置账户推广地域
	 *
	 * @return
	 */
	public function updateRegionTarget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:regiontarget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$regionName = '';
		$regionTarget = [];
		$regionPriceFactor = [];
		$regionTargetData = $request->param('regionTarget', '', 'trim');
		$regionTargetArray = json_decode($regionTargetData);
		if(count($regionTargetArray ) > 0){
			$cityNumber = 0;
			foreach( $regionTargetArray as $value) {
				if(in_array($value->id, [ 1000, 2000, 3000, 33000, 34000, 35000, 36000])) {
					$cityNumber++;
			    $regionName = $value->label;
					array_push($regionTarget, $value->id);
					array_push($regionPriceFactor, ['regionId'=> $value->id, 'priceFactor'=>$value->priceFactor]);
				}
				foreach( $value->children as $key => $item) {
					if($key == 0 ) {
						$regionName = $item->label;
					}
					$cityNumber++;
					array_push($regionTarget, $item->id);
					array_push($regionPriceFactor, ['regionId'=> $item->id, 'priceFactor'=>$item->priceFactor]);
				}
			}
			$regionName = $regionName . '等' . $cityNumber . '个';
		}

		if( count($regionTarget) == 0 ){
			return ['code'=>403, 'msg'=>'请至少选择一个地域!'];
		}

		$token = $request->param('token', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$updateAccountInfo = [
			'header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
			'body'=>[ 'accountInfo' =>	[
				'regionTarget'=> $regionTarget,
				'regionPriceFactor'=> $regionPriceFactor,
			]
		]];

		$result = doPostRequest('https://api.baidu.com/json/sms/service/AccountService/updateAccountInfo', json_encode($updateAccountInfo));
		if(empty($result)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		$response = json_decode($result, true);
		if(!is_array($response)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
    if(!isset($response['header'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
    if(!isset($response['header']['desc'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		if($response['header']['desc'] == 'success') {
			Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update([
				'regionName' => $regionName,
				'regionTarget' => $regionTargetData,
			]);
			return ['code'=> 0, 'msg'=> '操作成功!'];
		}
    if(!isset($response['header']['failures'])) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		return ['code'=> 403, 'msg'=> $response['header']['failures'][0]['code'] . ': '. $response['header']['failures'][0]['message']];
	}

	/**
	* 更新账户数据
	*
	* @param tValue
	* @return
	*/
	private function updateAccountInfo($parameter) {
		$request = doPostRequest('https://api.baidu.com/json/sms/service/AccountService/updateAccountInfo', $parameter);
		if(empty($request)) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		if(!isset($result['header']['desc'])) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		return $result;
	}

	/**
	 * 批量设置账户推广地域
	 *
	 * @return
	 */
	public function updateRegionTargetBatch(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:regiontarget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$ids = $request->param('ids', '', 'trim');
		if(empty($ids)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$regionName = '';
		$regionTarget = [];
		$regionPriceFactor = [];
		$regionTargetData = $request->param('regionTarget', '', 'trim');
		$regionTargetArray = json_decode($regionTargetData);
		if(count($regionTargetArray ) > 0){
			$cityNumber = 0;
			foreach( $regionTargetArray as $value) {
				if(in_array($value->id, [ 1000, 2000, 3000, 33000, 34000, 35000, 36000])) {
					$cityNumber++;
			    $regionName = $value->label;
					array_push($regionTarget, $value->id);
					array_push($regionPriceFactor, ['regionId'=> $value->id, 'priceFactor'=>$value->priceFactor]);
				}
				foreach( $value->children as $key => $item) {
					if($key == 0 ) {
						$regionName = $item->label;
					}
					$cityNumber++;
					array_push($regionTarget, $item->id);
					array_push($regionPriceFactor, ['regionId'=> $item->id, 'priceFactor'=>$item->priceFactor]);
				}
			}
			$regionName = $regionName . '等' . $cityNumber . '个';
		}

		if( count($regionTarget) == 0 ) {
			return ['code'=>403, 'msg'=>'请至少选择一个地域!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_expand')->field('id, username, password, token')->where('companyId', $request->sessInfo['companyId'])
		->where('userType', 1)->where('id', 'in', $ids)->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$response = $this->updateAccountInfo(json_encode([
					'header'=> [ 'username'=> $value['username'], 'password'=> $value['password'], 'token'=> $value['token'] ],
					'body'=> [ 'accountInfo' =>	[
						'regionTarget'=> $regionTarget,
						'regionPriceFactor'=> $regionPriceFactor,
					]
				]]));
				if($response['header']['desc'] == 'success') {
					Db::name('cfg_expand')->where('id', $value['id'])->update([
						'regionName' => $regionName,
						'regionTarget' => $regionTargetData,
					]);
					$endTime = microtime(true);
					$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
					$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM账户管理', '设置账号推广地域' , 0, null);
						array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['username'].'] 操作成功.</span>');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['username'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
					}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}

	/**
	 * 更新OCPC回传方式
	 *
	 * @return
	 */
	public function updateOcpc(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:ocpc')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$type = $request->param('type/d', '', 'trim');
		if(empty($type)) {
			return ['code'=>403, 'msg'=>'回传方式不能为空!'];
		}
		$beginTime = microtime(true);
		$typeName = $type == 1 ? '自动模式' :  '手动模式';
		$ocpcTime = $request->param('ocpcTime/d', '', 'trim');
		$arrayTemp = Db::table('cfg_expand')->field('username, ocpcType')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->select()->toArray();
		Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update(['ocpcType' => $type, 'ocpcTime' => $ocpcTime]);
		foreach( $arrayTemp as $value ) {
			$endTime = microtime(true);
			$ocpcName = $value['ocpcType'] == 1 ? '自动模式' :  '手动模式';
			$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
			$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM竞价', "推广账号[{$value['username']}]回传方式从[{$ocpcName}]改为[{$typeName}]", 0, null);
		}
		return ['code'=> 0, 'msg'=> '操作成功!'];
	}

	/**
	 * 更新用户资料
	 *
	 * @return
	 */
	public function updateUser(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'sem:refresh')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$query = Db::table('cfg_expand')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->find();
		if(!isset($query['id'])) {
			return ['code'=>403, 'msg'=>'非法请求id不存在!'];
		}

    $baiduUserArray = $this->getAccountInfo(json_encode(['header'=> [ 'username'=> $query['username'], 'password'=> $query['password'], 'token'=> $query['token'] ],
			'body'=> [ 'accountFields'=> [ 'regionTarget', 'mobileBalance', 'budgetType', 'pcBalance', 'userStat', 'balance', 'budget', 'cost', 'userId', 'regDomain', 'userLevel' ] ]]));
		if($baiduUserArray !== false ) {
			Db::name('cfg_expand')->where('id', $id)
					->update($baiduUserArray);
		}

		$baiduSiteArray = $this->getSiteList(json_encode(['header' => [ 'username'=> $query['username'], 'password'=> $query['password'], 'token'=> $query['token'], 'account_type'=> 1]]));
		if($baiduSiteArray !== false ) {
			Db::name('cfg_expand')->where('id', $id)
					->update($baiduSiteArray);
		}
		
		$getTargetPackageList = [
			'header'=> [ 'username'=> $query['username'], 'password'=> $query['password'], 'token'=> $query['token'] ],
			'body'=>[
				'targetPackageTypeFields' =>	[ "ocpcBid"],
				'ids' =>	[ 1	],
				'level' => 1
		]];

		$getOcpcService = doPostRequest('https://api.baidu.com/json/sms/service/OcpcService/getTargetPackageList', json_encode($getTargetPackageList));
		if($getOcpcService) {
				$response = json_decode($getOcpcService, true);
				if($response['header']['desc'] == 'success') {
						if(isset($response['body']['data'][0]['ocpcBid'])) {
							Db::name('cfg_expand')->where('id', $id)->update(['ocpcBid'=>$response['body']['data'][0]['ocpcBid']]);
						}
				}
		}

		return ['code'=> 0, 'msg'=> '操作成功!'];
	}

	/**
	 * 查询账号
	 *
	 * @return
	 */
	public function getQueryUrl(Request $request)
	{
		$url = $request->param('url', '', 'trim');
		if(empty($url)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('domainIds', $url)->value('domainIds');
		if(empty($query)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		return json(['code'=>0, 'data' => [['url' => $query]], 'msg'=>'']);
	}

	/**
	 * 查询推广地域
	 *
	 * @return
	 */
	public function regionTarget(Request $request)
	{
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$query = Db::table('cfg_expand')->field('id, regionTarget')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->find();
		if(!isset($query['id'])) {
			return ['code'=>403, 'msg'=>'非法请求id不存在!'];
		}
		$query['regionTarget'] = json_decode($query['regionTarget']);
		return json(['code'=>0, 'data' => $query, 'msg'=>'']);
	}

	/**
	 * 落地页列表
	 *
	 * @return
	 */
	public function getdomainUrl(Request $request) {
		return json(['code'=>0, 'website'=> Website::getList($request->sessInfo),
			'channel' => Channel::getList($request->sessInfo),
			'customer' => Customer::getList($request->sessInfo),
			'principal' => Principal::getList($request->sessInfo),
		  'bazaar' => Bazaar::getList($request->sessInfo, 1)]);
	}

	/**
	 * 查询账号
	 *
	 * @return
	 */
	public function query(Request $request)
	{
		$param = $request->param('param', '', 'trim');
		if(empty($param)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('username', $param)->value('username');
		if(empty($query)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		return json(['code'=>0, 'data' => [['username' => $query]], 'msg'=>'']);
	}

}
